package main

import (
	"fmt"
	"sync"
)

// 单例模式确保一个类仅有一个实例，并且提供一个全局访问点

// Singleton 单例结构体
type Singleton struct {
	data string
}

var instance *Singleton
var once sync.Once

// GetInstance 获取单例实例
func GetInstance() *Singleton {
	once.Do(func() {
		instance = NewSingleton("This is a singleton instance")
	})
	return instance
}

func NewSingleton(data string) *Singleton {
	fmt.Println("NewSingleton.")
	return &Singleton{data: data}
}

func main() {
	s1 := GetInstance()
	s2 := GetInstance()

	if s1 == s2 {
		fmt.Printf("Both instances are the same. data:%s \n", s1.data)
	}
}
